package hku.cs.lunuo.rank;

import hku.cs.lunuo.constant.DirAndFileConstant;
import hku.cs.lunuo.rank.model.Statistic;
import hku.cs.lunuo.rank.model.statistic.io.StatisticProvider;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class CDStatisticProvider extends StatisticProvider {

	@Override
	public Statistic readStatisticData(HashMap<String, Boolean> testResult)
			throws Exception {
		CDStatistic cdStatistic = new CDStatistic();
		Set<String> klassSet = new HashSet<String>();
		for (String key : testResult.keySet()) {
			cdStatistic.addTotaltf(testResult.get(key));
			File tf = new File(dataDir, key);
			if (tf.exists() && tf.isDirectory()) {
				File f = new File(tf, DirAndFileConstant.PRED);
				if (f.exists() && f.isDirectory()) {
					for (String kName : f.list()) {
						kName = kName.substring(0, kName.length() - 4);
						if (!klassSet.contains(kName)) {
							klassSet.add(kName);
							readPredData(dataDir, testResult, kName,
									cdStatistic);
						}
					}
				}
			}
		}
		return cdStatistic;
	}
	
	private void readPredData(File inDir, HashMap<String, Boolean> testResult,
			String name, CDStatistic cdStatistic) throws JDOMException,
			IOException {
		SAXBuilder sb = new SAXBuilder();
		for (String key : testResult.keySet()) {
			boolean tof = testResult.get(key);
			File tf = new File(inDir, key);
			if (tf.exists() && tf.isDirectory()) {
				File f = new File(tf, DirAndFileConstant.PRED);
				if (f.exists() && f.isDirectory()) {
					File iif = new File(f, name
							+ DirAndFileConstant.FILEEXTENTION);
					if (iif.exists() && iif.isFile()) {

						Document xmlDoc = sb.build(iif);
						Element xmlRoot = (Element) xmlDoc.getRootElement();
						String className = xmlRoot.getAttributeValue("name");

						Iterator xmlMethodIt = xmlRoot.getChildren("method")
								.iterator();
						while (xmlMethodIt.hasNext()) {
							Element xmlMethod = (Element) xmlMethodIt.next();
							String methodName = xmlMethod
									.getAttributeValue("name");
							Iterator xmlEsIt = xmlMethod.getChildren("es")
									.iterator();

							while (xmlEsIt.hasNext()) {
								Element xmlEs = (Element) xmlEsIt.next();
								String es = xmlEs.getAttributeValue("sequence");
								cdStatistic.add(className, methodName, es, tof);
							}
						}

					}
				}
			}
		}
	}

}
